package logic

import (
	"book-hub/models"
	"context"

	"book-hub/bookrpc/bookrpc"
	"book-hub/bookrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListNovelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListNovelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListNovelLogic {
	return &ListNovelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListNovelLogic) ListNovel(in *bookrpc.ListNovelRequest) (*bookrpc.ListNovelResponse, error) {
	// todo: add your logic here and delete this line
	off := (in.Page - 1) * in.Size
	var novel []models.NovelData
	models.DB.Model(models.Novel{}).
		Select("novels.*,  users.image,  users.`name`").
		Joins(" LEFT  JOIN users ON users.id = novels.user_id").
		Offset(int(off)).Limit(int(in.Size)).
		Where("novels.title like ?", "%"+in.Title+"%").
		Debug().
		Find(&novel)
	var listNovelData []*bookrpc.ListNovel
	for _, data := range novel {
		listNovel := bookrpc.ListNovel{
			Title:        data.Title,
			Class:        data.Class,
			Label:        data.Label,
			Introduction: data.Introduction,
			UserName:     data.Name,
			UserImage:    data.Image,
			NovelId:      int64(data.ID),
		}
		listNovelData = append(listNovelData, &listNovel)
	}
	return &bookrpc.ListNovelResponse{
		List: listNovelData,
	}, nil
}
